package com.heima.controller.resident;


import com.heima.Result;
import com.heima.domain.po.DrugOrder;
import com.heima.domain.query.DrugOrderQuery;
import com.heima.service.IDrugOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 * 药物订单表 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-08-04
 */
@Tag(name = "药物订单相关接口")
@RestController
@RequestMapping("/resident/drug-order")
public class DrugOrderController {
    @Autowired
    private IDrugOrderService drugOrderService;

    @Operation(summary = "分页查询药物订单")
    @GetMapping("/page")
    public Result findByPage(DrugOrderQuery drugOrderQuery) {
        return drugOrderService.findByPage(drugOrderQuery);
    }

    @Operation(summary = "新增药物订单")
    @PostMapping("/add")
    public Result add(@RequestBody DrugOrder drugOrder) {
        drugOrder.setStatus(1);
        drugOrder.setCreateTime(LocalDateTime.now());
        drugOrder.setUpdateTime(LocalDateTime.now());
        drugOrderService.save(drugOrder);
        return Result.success();
    }
    @Operation(summary = "修改药物订单状态")
    @PutMapping("/update")
    public Result update(Integer status, Integer id) {
        if (status == null || id == null) {
            return Result.error("状态或ID不能为空");
        }
        if(status < 1 || status > 3) {
            return Result.error("状态值不合法，必须在1到3之间");
        }
            DrugOrder drugOrder = drugOrderService.getById(id);
            if (drugOrder == null) return Result.error("订单不存在");
            if(status == 2 || status == 3 ) {
                return Result.error("只能处理未完成的订单");
            }
        drugOrder.setStatus(status);
        drugOrder.setUpdateTime(LocalDateTime.now());
        drugOrderService.updateById(drugOrder);
        return Result.success();
    }

    @Operation(summary = "根据id查询药物订单")
    @GetMapping("/get/{id}")
    public Result getById(@PathVariable Integer id) {
        DrugOrder drugOrder = drugOrderService.getById(id);
        if (drugOrder == null) {
            return Result.error("订单不存在");
        }
        return Result.success(drugOrder);
    }
}
